<script>
import {createProps} from '@/utils';
import {createField, createFormDefinition} from '@/components/hhd/design/FormDesigner/types';
import {getFieldConfigById} from '@/utils/FormDesignUtils';
import {getFieldComponent} from '@/components/hhd/design/FormDesigner/field/comps/FieldRegister';

export default {
  name: 'FieldConfig',
  props: {
    formDefinition: createProps(Object, createFormDefinition),
    selectedView: createProps(String),
    selectedField: createProps(String)
  },
  render(h) {
    if (!this.selectedField) return undefined;
    let component = this.getFieldConfigComponent();
    if (!component) return undefined;
    return h(component.config, {
      props: {
        fieldConfig: this.fieldConfig,
        formDefinition: this.formDefinition,
      }
    });
  },
  data() {
    return {
      fieldConfig: createField(),
    };
  },
  methods: {
    getFieldConfigComponent() {

      return this.fieldConfig && this.fieldConfig.component && getFieldComponent(this.fieldConfig.component) || undefined;
    },
    getField() {
      this.fieldConfig = getFieldConfigById(this.selectedField, this.formDefinition) || this.fieldConfig;
    },
  },
  watch: {
    selectedField: {
      handler() {
        this.$nextTick(() => {
          this.getField();
        });
      },
      immediate: true,
    }
  }
};
</script>
